package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.aliyun.oss.ServiceException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.ReservationMapper;
import com.zzyl.nursing.domain.Reservation;
import com.zzyl.nursing.service.IReservationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 预约信息Service业务层处理
 * 
 * @author alexis
 * @date 2025-09-13
 */
@Service
public class ReservationServiceImpl extends ServiceImpl<ReservationMapper, Reservation> implements IReservationService
{
    @Autowired
    private ReservationMapper reservationMapper;
    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    /**
     * 查询预约信息
     * 
     * @param id 预约信息主键
     * @return 预约信息
     */
    @Override
    public Reservation selectReservationById(Long id)
    {
        return reservationMapper.selectById(id);
    }

    /**
     * 查询预约信息列表
     * 
     * @param reservation 预约信息
     * @return 预约信息
     */
    @Override
    public List<Reservation> selectReservationList(Reservation reservation)
    {
        return reservationMapper.selectReservationList(reservation);
    }

    /**
     * 新增预约信息
     * 
     * @param reservation 预约信息
     * @return 结果
     */
    @Override
    public int insertReservation(Reservation reservation)
    {
        Long userId = UserThreadLocal.getUserId();
        FamilyMember familyMember = familyMemberMapper.selectFamilyMemberById(userId);
        reservation.setCreateBy(familyMember.getId().toString());
        reservation.setUpdateBy(familyMember.getId().toString());
        reservation.setCreateTime(new Date());
        reservation.setUpdateTime(new Date());
        reservation.setStatus(0);
        return reservationMapper.insert(reservation);
    }

    /**
     * 修改预约信息
     * 
     * @param reservation 预约信息
     * @return 结果
     */
    @Override
    public int updateReservation(Reservation reservation)
    {
        return reservationMapper.updateById(reservation);
    }

    /**
     * 批量删除预约信息
     * 
     * @param ids 需要删除的预约信息主键
     * @return 结果
     */
    @Override
    public int deleteReservationByIds(Long[] ids)
    {
        return reservationMapper.deleteBatchIds(Arrays.asList(ids));
    }
    @Override
    public int deleteReservationById(Long id)
    {
        return reservationMapper.deleteById(id);
    }

    @Override
    public Reservation selectReservationCancelledCount() {
        //从本地线程中取出userId
        Long userId = UserThreadLocal.getUserId();
        long time = System.currentTimeMillis();
        LocalDateTime ldt = LocalDateTimeUtil.of(time);
        LocalDateTime startTime = ldt.toLocalDate().atStartOfDay();
        LocalDateTime endTime = startTime.plusDays(1);
        return reservationMapper.selectOne(new LambdaQueryWrapper<Reservation>()
                .eq(Reservation::getStatus, 2)
                .ge(Reservation::getTime, startTime)   // 大于等于开始时间
                .lt(Reservation::getTime, endTime)
                .eq(Reservation::getUpdateBy, userId ));
    }
    @Override
    public List<Map<String, Object>> selectCountByTime(LocalDateTime startTime, LocalDateTime endTime) {
        return reservationMapper.selectCountByTime(startTime, endTime);
    }
    @Override
    public String cancelReservation(Long id) {
        try {
            // 1. 查询预约信息
            Reservation reservation = reservationMapper.selectById(id);

            // 2. 检查预约是否存在
            if (reservation == null) {
                throw new ServiceException("预约信息不存在");
            }

            // 3. 检查预约状态，只有待报道状态才能取消
            if (reservation.getStatus() != 0) { // 0: 待报道
                throw new ServiceException("只有待报道状态的预约才能取消");
            }

            // 4. 检查预约时间是否已过期
            if (reservation.getTime().isBefore(LocalDateTime.now())) {
                throw new ServiceException("预约时间已过期，无法取消");
            }

            // 5. 更新预约状态为取消(2)
            reservation.setStatus(2); // 2: 取消
            reservation.setUpdateTime(new Date( System.currentTimeMillis() ));

            // 6. 从线程中获取当前用户ID
            Long userId = UserThreadLocal.getUserId();
            if (userId != null) {
                reservation.setUpdateBy(String.valueOf(userId));
            }

            int result = reservationMapper.updateById(reservation);

            if (result > 0) {
                return "取消预约成功";
            } else {
                throw new ServiceException("取消预约失败");
            }
        } catch (ServiceException e) {
            throw e;
        } catch (Exception e) {
            log.error("取消预约失败", e);
            throw new ServiceException("取消预约失败: " + e.getMessage());
        }
    }



}
